package net.zui.action;

import java.awt.event.KeyEvent;
import net.zui.comp.ZBase;
import net.zui.comp.ZBaseFrame;
import net.zui.entity.ZBaseManager;
import net.zui.enume.ActionEnum;

public class WindowKeyAction extends ZKeyAction {
	private ZBaseFrame frame;
	private ZBaseManager manager;
	private ActionDispather action;
	private ZKeyAction keyAction;
	
	public WindowKeyAction(ZBaseFrame frame) {
		this.frame=frame;
		manager=frame.getManager();
		action=frame.getActionDispather();
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		dispather(e,ActionEnum.keyTyped,new KeyCallback() {
			@Override
			public void call(ZKeyAction keyAction) {
				keyAction.keyPressed(e);
			}
		});
	}
	
	@Override
	public void keyReleased(KeyEvent e) {
		dispather(e,ActionEnum.keyTyped,new KeyCallback() {
			@Override
			public void call(ZKeyAction keyAction) {
				keyAction.keyReleased(e);
			}
		});
	}
	
	@Override
	public void keyTyped(KeyEvent e) {
		dispather(e,ActionEnum.keyTyped,new KeyCallback() {
			@Override
			public void call(ZKeyAction keyAction) {
				keyAction.keyTyped(e);
			}
		});
	}
	
	private ZBase dispather(KeyEvent e,ActionEnum enume,KeyCallback back) {
		ZBase focus = manager.getFocus();
		if(focus!=null) {
			boolean res=action.keyEventFire(focus.getId(), ActionEnum.keyTyped, e);
			if(!res) {
				keyAction = focus.getOuterKey();
				if(keyAction!=null)back.call(keyAction);
			}
		}else {
			boolean res=action.keyEventFire("this", ActionEnum.keyTyped, e);
			if(!res) {
				keyAction=frame.getOuterKey();
				if(keyAction!=null)back.call(keyAction);
			}
		}
		return null;
	}
	
	static interface KeyCallback{
		void call(ZKeyAction keyAction);
	}
}
